import time
from .models import RequestLog
from uuid import uuid4


class RequestTimingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 生成唯一请求ID
        request.request_id = uuid4()

        # 记录开始时间
        start_time = time.time()

        # 处理请求
        response = self.get_response(request)

        # 计算耗时
        duration = time.time() - start_time

        # 保存到数据库
        RequestLog.objects.create(
            request_id=request.request_id,
            path=request.path,
            method=request.method,
            duration=duration,
            status_code=response.status_code
        )

        # 添加X-Request-ID头
        response['X-Request-ID'] = str(request.request_id)
        return response
